package com.techysky.aop;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.techysky.annoation.Operation;
import com.techysky.entity.SysLog;
import com.techysky.entity.User;
import com.techysky.repository.SysLogRepository;
/**
 * 所有的注解解析类均放在此处
 * @author zhangxu
 *
 */
@Aspect
@Component
public class ParseAnnoation {
	
	private static final Log log=LogFactory.getLog(ParseAnnoation.class);

    private ThreadLocal<SysLog> tlocal = new ThreadLocal<>();
    @Autowired
    private SysLogRepository sysLogRepository;

    @Pointcut("@annotation(com.techysky.annoation.Operation)")
    public void operation() {
    	throw new UnsupportedOperationException();
    }

    //@Order(1)
    @Before("operation()")
    public void doBefore(JoinPoint joinPoint) {
        try {
            // 接收到请求，记录请求内容
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            String methodName = joinPoint.getSignature().getName();
           User user = (User) request.getSession().getAttribute("user");
            Class<?> s = joinPoint.getSignature().getDeclaringType();  
            Method[] methods = s.getDeclaredMethods();
            Object[] arguments = joinPoint.getArgs(); 
            saveLog( methods,arguments,methodName,user.getUserName());
        } catch (Exception e) {
        	log.info(e);
        }
    }

    public void saveLog(Method[] methods,Object[] arguments,String methodName,String userName){
    	String description="";
        String type="";
        for (Method method : methods) {    
            if (method.getName().equals(methodName)) {    
               Class<?>[] clazzs = method.getParameterTypes();    
                if (clazzs.length == arguments.length) {    
                	description = method.getAnnotation(Operation.class).value();
                	type = method.getAnnotation(Operation.class).type(); 
                    break;    
               }    
           }    
       }
        SysLog optLog = new SysLog();
        optLog.setOperation(description);
        optLog.setType(type);
        optLog.setUserName(userName);
        tlocal.set(optLog);
    }
    //@Order(2)
    @AfterReturning(pointcut = "operation()")
    public void doAfterReturning() {
        // 处理完请求，返回内容
    	SysLog optLog = tlocal.get();
    	if(null!=optLog){
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	optLog.setCreateDate(sdf.format(Calendar.getInstance().getTime()));
    	optLog.setResult("成功");
    	sysLogRepository.save(optLog);
    	}
    }


}
